import 'package:enjoy_community_flutter/pages/home/index.dart';
import 'package:enjoy_community_flutter/pages/mine/index.dart';
import 'package:enjoy_community_flutter/utils/event_bud.dart';
import 'package:enjoy_community_flutter/utils/token.dart';
import 'package:flutter/material.dart';

class TabBarPage extends StatefulWidget {
  const TabBarPage({super.key});

  @override
  State<TabBarPage> createState() => _TabBarPageState();
}

class _TabBarPageState extends State<TabBarPage> {
  // 记录当前索引
  int currentIndex = 0;

  // 底部TabBar数据
  List tabBarList = [
    {
      "title": "首页",
      "default": "assets/tabs/home_default.png",
      "active": "assets/tabs/home_active.png"
    },
    {
      "title": "我的",
      "default": "assets/tabs/my_default.png",
      "active": "assets/tabs/my_active.png"
    }
  ];

  @override
  void initState() {
    super.initState();
    // 先获取token
    Future.delayed(Duration.zero, () async {
      await TokenManager().init();
    });
     // 订阅去登录的事件
    eventBus.on<ToLoginPageEvent>().listen((event) {
      // ignore: use_build_context_synchronously
      Navigator.pushNamed(context, '/login');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // IndexedStack 实现多个页面之间的切换，保持状态
      body: SafeArea(
        child: IndexedStack(
          index: currentIndex, // 索引
          children: [const HomePage(), MinePage(currentIndex: currentIndex,)],
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: barItemList(),
        type: BottomNavigationBarType.fixed,
        currentIndex: currentIndex,
        selectedItemColor: const Color.fromARGB(255, 85, 145, 175),
        unselectedItemColor: Colors.black,
        onTap: (index) {
          // 视图改变，需要使用setState
          setState(() {
            currentIndex = index;
          });
        },
      ),
    );
  }

  List<BottomNavigationBarItem> barItemList() {
    List<BottomNavigationBarItem> items = [];
    for (var item in tabBarList) {
      items.add(
        BottomNavigationBarItem(
            icon: Image.asset(
              item['default'],
              width: 32,
              height: 32,
            ),
            activeIcon: Image.asset(
              item['active'],
              width: 32,
              height: 32,
            ),
            label: item['title']),
      );
    }
    return items;
  }
}
